package com.ukao.pad.ui.setting;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.ukao.pad.R;
import com.ukao.pad.adapter.PrintAdapter;
import com.ukao.pad.base.BaseFragment;
import com.ukao.pad.bean.PrinterBean;
import com.ukao.pad.consts.Constant;
import com.ukao.pad.printer.CheckPrinterHelper;
import com.ukao.pad.printer.PrinterHelper;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.T;
import com.ukao.pad.widget.StateButton;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class PrintFragment extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    Unbinder unbinder;

    @BindView(R.id.data)
    TextView data;
    @BindView(R.id.download_btn)
    StateButton downloadBtn;
    @BindView(R.id.setting_btn)
    StateButton settingBtn;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private PrintAdapter mPrintAdapter;
    private String filePath;


    public static PrintFragment newInstance(String param1, String param2) {
        PrintFragment fragment = new PrintFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_setting_spear, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (CheckUtils.isAppInstalled()) {
            downloadBtn.setVisibility(View.GONE);

        } else {
            downloadBtn.setVisibility(View.VISIBLE);
        }

        List<PrinterBean> mData = CheckPrinterHelper.loadPrinterList();
        if (CheckUtils.isEmpty(mData)) {
            recyclerView.setVisibility(View.GONE);
            data.setVisibility(View.VISIBLE);

        } else {
            data.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            mPrintAdapter.setDatas(mData);
        }

    }

    @Override
    protected void initView() {

        initLinearRecyclerView(recyclerView);
        mPrintAdapter = new PrintAdapter(activity, CheckPrinterHelper.loadPrinterList());
        recyclerView.setAdapter(mPrintAdapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({ R.id.download_btn,R.id.setting_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.download_btn:
                download();

                break;
            case  R.id.setting_btn :
                Intent intent =  new Intent(Settings.ACTION_PRINT_SETTINGS);
                startActivity(intent);
                break;
        }
    }

    public String getVideoSavePath() {
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        String pathString = "";
        if (dcim.exists()) {
            pathString = dcim + "/XKXResource/print";
        } else {
            pathString = "/sdcard/XKXResource/print";
        }
        File videoPathFile = new File(pathString);
        if (!videoPathFile.exists()) {
            videoPathFile.mkdirs();
        }
        return pathString;
    }


    private void download() {
        filePath = getVideoSavePath();
        FileDownloader.getImpl().create(Constant.PRINT_SERVE)
                .setPath(filePath + "/printServe.apk")
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        double f = (double) soFarBytes * 100 / totalBytes;
                        DecimalFormat df = new DecimalFormat("######0.00");
                        String msgString = df.format(f) + "%";
                        showProgressDialog(msgString);

                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        dismissProgressDialog();
                        installAPK(new File(task.getPath()));

                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {


                        dismissProgressDialog();
                        T.show("下载失败");
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                }).start();
    }


    private void installAPK(File file) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);

    }


}
